package com.dhecp.project.system.controller;

import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.file.FileUploadUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.service.ModuleNidAndBidService;
import com.dhecp.project.system.domain.SysMailTableInfo;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysMailTableInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  C/S邮件系统2 控制层
 */

@Controller
@RequestMapping("/system/oamail")
public class SysMailTableInfoController extends BaseController {

    private String prefix = "system/oamail";
    private String moduleTable = ModuleTable.TS_SYSTEM_MAIL_TABLE_INFO;

    @Autowired
    private SysMailTableInfoService sysMailTableInfoService;

    @Autowired
    private ModuleNidAndBidService moduleNidAndBidService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    /**
     * 打开邮件系统主页面
     * @return ModelAndView
     */
    @GetMapping()
    public ModelAndView sysMailTableInfo(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        mv.setViewName(prefix + "/mail");
        return mv;
    }

    /**
     * 打开邮件系统列表页面
     * @param pageType 页面类型：收件箱（inbox）、发件箱（outbox）、草稿箱（draftbox）、保留邮件（savebox）、群发邮件（massbox）、已删除（deletedbox）
     * @return ModelAndView
     * @author DH-Xxj
     */
    @GetMapping("/mailList")
    public ModelAndView mailList(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> gridColumns = new HashMap<String, Object>();
    	params.put("entity", new SysMailTableInfo());
        params.put("toolBarWidth", 0);
        params.put("readOnly", false);
        params.put("checkBox", "yes");
        params.put("moduleTable", moduleTable);
        gridColumns = gridColumnsPropertyModel.queryGridColumnsPropertyModel(params);
        String fileViewUrl = FileUploadUtils.getFileViewUrl();
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("pageType", params.get("pageType").toString());
        mv.addObject("moduleTable", moduleTable);
        mv.addObject("gridColumns", gridColumns);
        mv.addObject("prefix", prefix);
        mv.addObject("fileViewUrl", fileViewUrl);
        mv.setViewName(prefix + "/mail_list");
        return mv;
    }

    /**
     *	打开邮件系统新增、编辑、查看页面
     *	@param guid 行唯一值guid，新增可省略
     *	@param pageType 页面类型：新增（add）、编辑（edit）、回复（reply）、转发（transport）、查看（readonly）
     * 	新增（add）：可编辑页面，所有内容为空
     *	 编辑（edit）：可编辑页面，带出当前邮件所有内容，包括隐藏和显示的内容，适用于打开草稿进行编辑
     *	 回复（reply）：可编辑页面，带出当前邮件所有内容，包括隐藏和显示的内容；原发件人变为收件人，抄送\密送为空（可重新选择），mailGuid赋值给pGuid
     *	 转发（transport）：可编辑页面，带出当前邮件所有内容，包括隐藏和显示的内容；收件人\抄送\密送为空（可重新选择），mailGuid赋值给pGuid
     *	 查看（readonly）：不可编辑页面，带出当前邮件所有内容，包括隐藏和显示的内容
     * @return
     * @author DH-Xxj
     */
    @GetMapping("/edit")
    public ModelAndView mailContentEdit(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        String pageType = "readonly";
        if (params.get("pageType") != null && params.get("pageType") != ""){
        	pageType = params.get("pageType").toString().toLowerCase();
        }
        SysMailTableInfo mailContent = new SysMailTableInfo();
        switch(pageType) {
        	case "add":
            	mailContent.setId(RandomValueUtils.getGUID());//附件关联字段，用于新增邮件时关联附件
        		break;
        	case "edit":
        	case "reply":
        	case "transport":
            	if (params.get("id") == null || params.get("id") == ""){
            		return this.gotoModelAndViewErrorPage("请提供必要参数：id。");
            	}
        		mailContent = sysMailTableInfoService.queryMailByID(params.get("id").toString());
        		if(!pageType.equals("edit")) {
                	mailContent.setId(RandomValueUtils.getGUID());//附件关联字段，用于新增邮件时关联附件
        		}
            	mailContent.setParentID(mailContent.getId());
        		break;
        }
        mv.addObject("moduleTable", moduleTable);
        mv.addObject("pageType", pageType);//页面类型：新增（add）、编辑（edit）、回复（reply）、转发（transport）、查看（readonly）
        mv.addObject("mailContent", mailContent);//邮件内容
        mv.addObject("mailDelDays", ShiroUtils.getSystemSet().getMailDelDays());	//非保留邮件保留天数（超期转已删除）
        if ("readonly".equals(pageType)){
            mv.setViewName(prefix + "/mail_view");
        }else{
            mv.setViewName(prefix + "/mail_edit");
        }
        return mv;
    }

    /**
     *	查询邮件列表
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo listByNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<SysMailTableInfo> list = new ArrayList<SysMailTableInfo>();
        try {
            if (params.get("pageType") == null) {
                return getDataTable("页面类型【pageType】不能为空！");
            } else {
            	switch (params.get("pageType").toString().toLowerCase()) {
            		case "inbox"://收件箱
                        params.put("mailDraft", 0);//草稿邮件
                        params.put("reciveDeleted", 0);//收件人删除至回收站标志
                        params.put("reciveHided", 0);//收件人从回收站再删除标志
                        params.put("sendDeleted", 0);//发送人删除至回收站标志
                        params.put("sendHided", 0);//发送人从回收站再删除标志
                        // params.put("reciveID", ShiroUtils.getUserId());//接收人
                        list = sysMailTableInfoService.queryMailList(params);
            			break;
            		case "draftbox"://草稿箱
                        params.put("mailDraft", 1);//草稿邮件
                        params.put("reciveDeleted", 0);//收件人删除至回收站标志
                        params.put("reciveHided", 0);//收件人从回收站再删除标志
                        params.put("sendDeleted", 0);//发送人删除至回收站标志
                        params.put("sendHided", 0);//发送人从回收站再删除标志
                        params.put("sendID", ShiroUtils.getUserId());//发件人是自己
                        list = sysMailTableInfoService.queryMailList(params);
            			break;
            		case "outbox"://发件箱
                        params.put("mailDraft", 0);//草稿邮件
                        params.put("reciveDeleted", 0);//收件人删除至回收站标志
                        params.put("reciveHided", 0);//收件人从回收站再删除标志
                        params.put("sendDeleted", 0);//发送人删除至回收站标志
                        params.put("sendHided", 0);//发送人从回收站再删除标志
                        // params.put("fromUser", ShiroUtils.getUserId());
                        list = sysMailTableInfoService.queryMailList(params);
            			break;
            		case "savebox"://保留邮件
                        params.put("mailDraft", 0);//草稿邮件
                        params.put("reciveDeleted", 0);//收件人删除至回收站标志
                        params.put("reciveHided", 0);//收件人从回收站再删除标志
                        params.put("sendDeleted", 0);//发送人删除至回收站标志
                        params.put("sendHided", 0);//发送人从回收站再删除标志
                        // params.put("recUser", ShiroUtils.getUserId());
                        list = sysMailTableInfoService.queryMailList(params);
            			break;
            		case "massbox"://群发邮件
                        params.put("mailDraft", 0);//草稿邮件
                        params.put("reciveDeleted", 0);//收件人删除至回收站标志
                        params.put("reciveHided", 0);//收件人从回收站再删除标志
                        params.put("sendDeleted", 0);//发送人删除至回收站标志
                        params.put("sendHided", 0);//发送人从回收站再删除标志
                        // params.put("fromUser", ShiroUtils.getUserId());
                        list = sysMailTableInfoService.queryMailList(params);
            			break;
            		case "deletedbox"://回收站
                        params.put("mailDraft", 0);//草稿邮件
                        params.put("reciveDeleted", 0);//收件人删除至回收站标志
                        params.put("reciveHided", 0);//收件人从回收站再删除标志
                        params.put("sendDeleted", 0);//发送人删除至回收站标志
                        params.put("sendHided", 0);//发送人从回收站再删除标志
                        // params.put("recUser", ShiroUtils.getUserId());
                        list = sysMailTableInfoService.queryMailList(params);
            			break;
        			default:
        				return getDataTable("页面类型【pageType】无效。");
            	}
            }
        } catch (Exception e) {
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }
    
    /**
     *	查询邮件列表存储过程
     * @return
     */
    @GetMapping("/listByProcedure")
    @ResponseBody
    public TableDataInfo findSystemMailList(@RequestParam Map<String, Object> params){
        List<SysMailTableInfo> list = new ArrayList<SysMailTableInfo>();
        Integer countRow = 0;
        try {
            if (params.get("pageType") == null) {
                return getDataTable("页面类型【pageType】不能为空！");
            } else {
            	switch (params.get("pageType").toString().toLowerCase()) {
            		case "inbox"://收件箱
            			params.put("MailKind", "MtPrivateMail");//邮箱类型
            			break;
            		case "draftbox"://草稿箱
            			params.put("MailKind", "MtDraftMail");//邮箱类型
            			break;
            		case "outbox"://发件箱
            			params.put("MailKind", "MtSendMail");//邮箱类型
            			break;
            		case "savebox"://保留邮件
            			params.put("MailKind", "MtSaveMail");//邮箱类型
            			break;
            		case "massbox"://群发邮件
            			params.put("MailKind", "MtPublicMail");//邮箱类型
            			break;
            		case "deletedbox"://回收站
            			params.put("MailKind", "MtDeleteMail");//邮箱类型
            			break;
        			default:
        				return getDataTable("页面类型【pageType】无效。");
            	}
    			params.put("UserID", ShiroUtils.getUserId());//登录用户工号
    			params.put("UserCaption", ShiroUtils.getUserName());//登录用户姓名
    			params.put("DepartmentID", ShiroUtils.getUserDeptId());//登录用户部门
                list = sysMailTableInfoService.findSystemMailList(params);
                if (list != null && list.size() > 0){
                    countRow = list.get(0).getCountRow();
                }
            }
        } catch (Exception e) {
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list,countRow);
    }
    
    /**
     *	搜索邮件列表存储过程
     * @return
     */
    @GetMapping("/searchByProcedure")
    @ResponseBody
    public TableDataInfo querySystemMailList(@RequestParam Map<String, Object> params){
        List<SysMailTableInfo> list = new ArrayList<SysMailTableInfo>();
        Integer countRow = 0;
        try {
            if (params.get("MailKind") == null) {
                return getDataTable("邮件类型【MailKind】不能为空！");
            } else {
    			params.put("UserID", ShiroUtils.getUserId());//登录用户工号
    			params.put("UserCaption", ShiroUtils.getUserName());//登录用户姓名
    			params.put("DepartmentID", ShiroUtils.getUserDeptId());//登录用户部门
                list = sysMailTableInfoService.querySystemMailList(params);
                if (list != null && list.size() > 0){
                    countRow = list.get(0).getCountRow();
                }
            }
        } catch (Exception e) {
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list,countRow);
    }

    /**
     * 	通过iD查询邮件
     * @param iD
     * @return MessageModel
     * @throws Exception
     */
    @RequestMapping("/listById")
    @ResponseBody
    public AjaxResult listById(@RequestParam Map<String, Object> params){
    	if (params.get("id") == null || params.get("id") == ""){
    		return AjaxResult.error("请提供必要参数：id。");
    	}
        AjaxResult ajaxResult = new AjaxResult();
        try{
        	SysMailTableInfo mailInfo = sysMailTableInfoService.queryMailByID(params.get("id").toString());
            if (mailInfo == null){
                ajaxResult =  AjaxResult.error("没有符合条件的数据。");
            }else{
                ajaxResult = AjaxResult.success("查询成功。", mailInfo);
            }
        }catch(Exception e){
            ajaxResult =  AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 	查询未读通知数
     * @param params
     * @return
     */
    @GetMapping("/listwds")
    @ResponseBody
    public AjaxResult listWds(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
			params.put("reciveID", ShiroUtils.getUserId());//登录用户
        	Integer mailWdCount = sysMailTableInfoService.querySystemMailWds(params);
            ajaxResult = AjaxResult.success("查询成功。", mailWdCount);
        } catch (Exception e) {
            ajaxResult =  AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     *	邮件已读操作
     *	更行标记并且更具iD删除 TS_SystemMailTableIndex 对应数据
     * @param infoItems （个人：id，mailRead，readTime）
     * @return AjaxResult
     */
    @PostMapping("/readedpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult updateReadedPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("infoItems") == null || params.get("infoItems") == ""){
        	return AjaxResult.error("缺少参数infoItems【对应实体类的json格式字符串】。");
        }
        try {
//        	ajaxResult= mailContentService.updateReaded(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     *	保存数据
     * @return
     */
    @PostMapping("/insertMail")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult insertMail(@RequestParam("mailInfoItems") String baseInfoItems){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= sysMailTableInfoService.insertMail(baseInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     *	修改邮件
     * @param mailInfoItems
     */
    @PostMapping("/updateMail")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult updateMail(@RequestParam Map<String, Object> params){
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(params)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= sysMailTableInfoService.updateMail(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     *	修改邮件数据
     * @param mailInfoItems
     */
    @PostMapping("/deleteMail")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult deleteMail(@RequestParam("mailInfoItems") String mailInfoItems) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(mailInfoItems)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= sysMailTableInfoService.deleteMail(mailInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

}